package com.itany.controller;

import com.github.pagehelper.PageInfo;
import com.itany.constant.StatusConst;
import com.itany.pojo.Role;
import com.itany.service.RoleService;
import com.itany.vo.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    RoleService roleService;

    @RequestMapping("/add")
    public ActionResult add(String name, @RequestParam("pids[]") Integer[] pids) {
        ActionResult result = new ActionResult();
        try {
            roleService.addRole(name, pids);
        } catch (Exception e) {
            result.setStatus(StatusConst.FAIL_RESPONSE);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping("/update")
    public ActionResult update(@RequestParam(required = true) Integer id, String name, @RequestParam("pids[]") Integer[] pids) {
        ActionResult result = new ActionResult();
        try {
            roleService.updateRole(id, name, pids);
        } catch (Exception e) {
            result.setStatus(StatusConst.FAIL_RESPONSE);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping("/delete")
    public ActionResult delete(Integer id) {
        ActionResult result = new ActionResult();
        try {
            roleService.delete(id);
        } catch (Exception e) {
            result.setStatus(StatusConst.FAIL_RESPONSE);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @RequestMapping("/findAll")
    public Map<String, Object> findAll(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            String name) {
        Map<String, Object> map = new HashMap<String, Object>();
        PageInfo<Role> info = roleService.findAll(page, rows, name);
        map.put("total", info.getTotal());
        map.put("rows", info.getList());
        return map;
    }

    @RequestMapping("/findAll2")
    public List<Map<String, Object>> findAll() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Role> info = roleService.findAll();
        info.forEach(role -> {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id",role.getId());
            map.put("text",role.getName());
            list.add(map);
        });

        return list;
    }
}
